package net.ecpt.hrm.services;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.util.UUID;

/**
 * 获得全球不重复的序列号
 */
public class IDGenerator {
	private static String tHexServerIP = null;
	private static final SecureRandom tSecureRandom = new SecureRandom();

	/**
	 * 获得全球不重复的序列号
	 * @return String 全球不重复的序列号
	 */
	public static String generateGUID() {
		Object tObject = new Object();
		StringBuffer tStringBuffer = new StringBuffer(16);
		if (tHexServerIP == null) {
			InetAddress tInetAddress = null;
			try {
				tInetAddress = InetAddress.getLocalHost();
			} catch (UnknownHostException uhe) {
				uhe.printStackTrace();
				return null;
			}
			byte tServerIP[] = tInetAddress.getAddress();
			tHexServerIP = hexFormat(getInt(tServerIP), 8);
		}
		String tHashCode = hexFormat(System.identityHashCode(tObject), 8);
		tStringBuffer.append(tHexServerIP);
		tStringBuffer.append(tHashCode);
		long tTimeNow = System.currentTimeMillis();
		int tTimeLow = (int) tTimeNow & -1;
		int tNode = tSecureRandom.nextInt();
		StringBuffer tGuid = new StringBuffer(32);
		tGuid.append(hexFormat(tTimeLow, 8));
		tGuid.append(tStringBuffer.toString());
		tGuid.append(hexFormat(tNode, 8));
		return tGuid.toString().toUpperCase();
	}
	
	public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g", "h",
        "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
        "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D",
        "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
        "T", "U", "V", "W", "X", "Y", "Z" };

	public synchronized static String generateShortUuid(){
	    StringBuffer shortBuffer=new StringBuffer();
	    String uuid=UUID.randomUUID().toString().replace("-","");
	    for(int i=0;i< 4;i++){
	         String str=uuid.substring(i*4,i*4+4);
	         int x=Integer.parseInt(str,16);
	         shortBuffer.append(chars[x%0x3E]);
	    }
	    return shortBuffer.toString();
    }
	
	private static int getInt(byte bytes[]) {
		int i = 0;
		int j = 24;
		for (int k = 0; j >= 0; k++) {
			int l = bytes[k] & 0xff;
			i += l << j;
			j -= 8;
		}

		return i;
	}

	private static String hexFormat(int i, int j) {
		String tString = Integer.toHexString(i);
		return padHex(tString, j) + tString;
	}

	private static String padHex(String s, int i) {
		StringBuffer tStringBuffer = new StringBuffer();
		if (s.length() < i) {
			for (int j = 0; j < i - s.length(); j++)
				tStringBuffer.append('0');

		}
		return tStringBuffer.toString();
	}
	
	
	public static String getId() {
	    return IDGenerator.generateGUID().substring(0,20);
	}
	
	public static void main(String[] args) {
		System.out.println(getId());
	}
}

